import G from "../Utilities/Global";

/**
 * 关卡结算界面
 * created by Five on 2018-12-21 17:00:26
 */
const { ccclass, property } = cc._decorator

@ccclass
export default class UIGameEnd extends cc.Component {
    @property(cc.Node)
    touchPrevent: cc.Node = null;

    @property(cc.Node)
    winNode: cc.Node = null;

    @property(cc.Node)
    loseNode: cc.Node = null;

    @property(cc.Node)
    btnLeft: cc.Node = null;

    @property(cc.Node)
    btnRight: cc.Node = null;

    private result: boolean = false;

    start() {
        this.touchPrevent.on(cc.Node.EventType.TOUCH_START, (e: Event) => {
            e.stopPropagation();
        });

        this.node.opacity = 0;
        this.node.runAction(cc.sequence(cc.fadeIn(0.5), cc.callFunc(() => {
            cc.director.pause();
        })));
    }

    Gameend(win: boolean) {
        this.result = win;
        this.changeForm();
        this.changeButtons();
    }

    private changeForm() {
        this.winNode.active = this.result;
        this.loseNode.active = !this.result;
    }

    leftClick() {
        if (this.result) {
            G().CurScene.Restart();
        } else {
            G().ToMainScene();
        }
        cc.director.resume();
        G().Sound.playSFX("btn_clicked");
    }

    rightClick() {
        if (this.result) {
            G().CurScene.Next();
        } else {
            G().CurScene.Restart();
        }
        cc.director.resume();
        G().Sound.playSFX("btn_clicked");
        this.node.removeFromParent();
    }

    private changeButtons() {
        if (this.result) {
            this.changeSprite(this.btnLeft, "restart");
            this.changeSprite(this.btnRight, "next");
        } else {
            this.changeSprite(this.btnLeft, "tomain");
            this.changeSprite(this.btnRight, "restart");
        }
    }

    /**
     * 
     * @param node node
     * @param pName 资源名
     */
    private async changeSprite(node: cc.Node, pName: string) {
        let affix = "gameover/";
        let sprite = node.getChildByName("sprite").getComponent(cc.Sprite);
        let spframe = await G().Res.GetSpriteFrame(affix + pName) as cc.SpriteFrame
        sprite.spriteFrame = spframe;
    }
}